#!/usr/bin/env bash

set -o xtrace

# Keep track of the current devstack directory.
TOP_DIR=$(cd $(dirname "$0") && pwd)

PUBLIC_IP=`ip a show dev eth0 | grep 'inet ' | awk '{print $2}' | cut -d\/ -f1`
PRIVATE_PREFIX=${PRIVATE_PREFIX:-"192.168.3"}
PRIVATE_IP=${PRIVATE_IP:-"192.168.3.69"}
FIXED_RANGE_PREFIX=${FIXED_RANGE_PREFIX:-"172.20.1"}

# prepare to install
# /apt/source/source.list
SOURCE_FILE=${SOURCE_FILE:-"/etc/apt/sources.list"}
sed -i 's/us.archive.ubuntu.com/mirrors.163.com/g' $SOURCE_FILE
sudo apt-get update
# Helper to clean iptables rules
function clean_iptables() {
    # Delete rules
    sudo iptables -S -v | sed "s/-c [0-9]* [0-9]* //g" | grep "nova" | grep "\-A" |  sed "s/-A/-D/g" | awk '{print "sudo iptables",$0}' | bash
    # Delete nat rules
    sudo iptables -S -v -t nat | sed "s/-c [0-9]* [0-9]* //g" | grep "nova" |  grep "\-A" | sed "s/-A/-D/g" | awk '{print "sudo iptables -t nat",$0}' | bash
    # Delete chains
    sudo iptables -S -v | sed "s/-c [0-9]* [0-9]* //g" | grep "nova" | grep "\-N" |  sed "s/-N/-X/g" | awk '{print "sudo iptables",$0}' | bash
    # Delete nat chains
    sudo iptables -S -v -t nat | sed "s/-c [0-9]* [0-9]* //g" | grep "nova" |  grep "\-N" | sed "s/-N/-X/g" | awk '{print "sudo iptables -t nat",$0}' | bash
}
#sudo killall dnsmasq
#clean_iptables
#rm -rf $NOVA_DIR/networks
#mkdir -p $NOVA_DIR/networks
sudo sysctl -w net.ipv4.ip_forward=1
	
# Destroy old instances
INSTANCE_NAME_PREFIX=${INSTANCE_NAME_PREFIX:-instance-}
instances=`sudo virsh list --all | grep $INSTANCE_NAME_PREFIX | sed "s/.*\($INSTANCE_NAME_PREFIX[0-9a-fA-F]*\).*/\1/g"`
if [ ! "$instances" = "" ]; then
    echo $instances | xargs -n1 sudo virsh destroy || true
    echo $instances | xargs -n1 sudo virsh undefine || true
fi

# chkconfig
sudo apt-get install chkconfig
sudo chkconfig libvirt-bin on
sudo chkconfig rabbitmq-server on

# bridge-utils
sudo apt-get install -y bridge-utils
	
# network configure
NETWORK_CONF=${NETWORK_CONF:-"/etc/network/interfaces"}
DNS_CONF=${DNS_CONF:-"/etc/resolv.conf"}
DNS_ADDRESS=${DNS_ADDRESS:-"202.119.32.6"}
if ! grep -q eth1 $NETWORK_CONF; then
	echo "auto eth1" >> $NETWORK_CONF
	echo "iface eth1 inet static" >> $NETWORK_CONF
	echo "    address $PRIVATE_IP" >> $NETWORK_CONF
	echo "    netmask 255.255.255.0" >> $NETWORK_CONF
	echo "    network $PRIVATE_PREFIX.0" >> $NETWORK_CONF
	echo "    broadcast $PRIVATE_PREFIX.255" >> $NETWORK_CONF
	sudo /etc/init.d/networking restart
fi

if ! grep -q $DNS_ADDRESS $DNS_CONF; then
	echo "nameserver $DNS_ADDRESS" >> $DNS_CONF
fi

# ntp
sudo apt-get install -y ntp
if ! grep -q fudge "/etc/ntp.conf"; then
	sudo sed -i 's/server ntp.ubuntu.com/server ntp.ubuntu.com\nserver127.127.1.0\nfudge 127.127.1.0 stratum 10/g' /etc/ntp.conf
	sudo service ntp restart
fi

# MySQL
MYSQL_PASSWD=${MYSQL_PASSWD:-"hezudaopp"}
MYSQL_CONF=${MYSQL_CONF:-"/etc/mysql/my.cnf"}
sudo apt-get install -y python-mysqldb mysql-server
sudo chkconfig mysql on
sudo sed -i 's/127.0.0.1/0.0.0.0/g' $MYSQL_CONF
sudo restart mysql
	
# keystone
#KEYSTONE_PASS=${KEYSTONE_PASS:-"hezudaopp"}
#KEYSTONE_PORT=${KEYSTONE_PORT:-"5001"}
#KEYSTONE_CONF_FILE=${KEYSTONE_CONF_FILE:-"/etc/keystone/keystone.conf"}
#KEYSTONE_ADMIN_TOKEN=${KEYSTONE_ADMIN_TOKEN:-"012345SECRET99TOKEN012345"}
#sudo apt-get install -y keystone
#sudo rm /var/lib/keystone/keystone.db
#mysql -u root -p$MYSQL_PASSWD -e "CREATE DATABASE keystone;"
#mysql -u root -p$MYSQL_PASSWD -e "GRANT ALL ON keystone.* TO 'keystone'@'%' IDENTIFIED BY '$KEYSTONE_PASS';"
#sed -i '/connection = .*/{s|sqlite:///.*|mysql://keystone:'"$MYSQL_PASSWD"'@'"$PUBLIC_IP"'/keystone|g}' $KEYSTONE_CONF_FILE
#sed -i 's|^admin_port.*|&\nadmin_token = '"$KEYSTONE_ADMIN_TOKEN"'|g' $KEYSTONE_CONF_FILE
#sed -i 's|^admin_port.*|admin_port = '"$KEYSTONE_PORT"'|g' $KEYSTONE_CONF_FILE
# TODO:configure service to work with keystone
#sudo service keystone restart
#sudo keystone-manage db_sync

# install glance
GLANCE_DB_USERNAME=${GLANCE_DB_USERNAME:-"glancedbadmin"}
GLANCE_DB_PASSWD=${GLANCE_DB_PASSWD:-"hezudaopp"}
GLANCE_API_CONF=${GLANCE_API_CONF:-"/etc/glance/glance-api.conf"}
GLANCE_REGISTRY_CONF=${GLANCE_REGISTRY_CONF:-"/etc/glance/glance-registry.conf"}
sudo apt-get install -y glance
sudo rm /var/lib/glance/glance.sqlite
sudo mysql -uroot -p$MYSQL_PASSWD -e "DROP DATABASE IF EXISTS glance;"
sudo mysql -uroot -p$MYSQL_PASSWD -e "CREATE DATABASE glance;"
sudo mysql -uroot -p$MYSQL_PASSWD -e "CREATE USER $GLANCE_DB_USERNAME;"
sudo mysql -uroot -p$MYSQL_PASSWD -e "GRANT ALL ON glance.* TO '$GLANCE_DB_USERNAME'@'%' IDENTIFIED BY '$GLANCE_DB_PASSWD';"
sed -i '/sql_connection = .*/{s|sqlite:///.*|mysql://'"$GLANCE_DB_USERNAME"':'"$GLANCE_DB_PASSWD"'@'"$PUBLIC_IP"'/glance|g}' $GLANCE_API_CONF
sed -i '/sql_connection = .*/{s|sqlite:///.*|mysql://'"$GLANCE_DB_USERNAME"':'"$GLANCE_DB_PASSWD"'@'"$PUBLIC_IP"'/glance|g}' $GLANCE_REGISTRY_CONF
sudo service glance-api restart
sudo service glance-registry restart
	
# nova
NOVA_DB_USERNAME=${NOVA_DB_USERNAME:-"novadbadmin"}
NOVA_DB_PASSWD=${NOVA_DB_PASSWD:-"hezudaopp"}
sudo apt-get install -y rabbitmq-server nova-common nova-doc python-nova nova-api nova-network nova-volume nova-objectstore nova-scheduler nova-compute
sudo apt-get install -y euca2ools
sudo apt-get install -y unzip
sudo mysql -uroot -p$MYSQL_PASSWD -e "DROP DATABASE IF EXISTS nova;"
sudo mysql -uroot -p$MYSQL_PASSWD -e "CREATE DATABASE nova;"
sudo mysql -uroot -p$MYSQL_PASSWD -e "CREATE USER $NOVA_DB_USERNAME;"
sudo mysql -uroot -p$MYSQL_PASSWD -e "GRANT ALL ON nova.* TO '$NOVA_DB_USERNAME'@'%' IDENTIFIED BY '$NOVA_DB_PASSWD';"

# TODO: nova-volumn configuration
	
# nova configuration
NOVA_DIR=${NOVA_DIR:-"/var/lib/nova"}
NOVA_CONF_DIR=${NOVA_CONF_DIR:-"/etc/nova"}
NOVA_CONF=${NOVA_CONF:-"nova.conf"}
NOVA_BUCKETS_DIR=${NOVA_BUCKETS_DIR:-"$NOVA_DIR/buckets"}
NOVA_INSTANCES_DIR=${NOVA_INSTANCES_DIR:="$NOVA_DIR/instances"}
rm -f $NOVA_CONF_DIR/$NOVA_CONF
rm -rf $NOVA_BUCKETS_DIR/*
rm -rf $NOVA_INSTANCES_DIR/*
rm -rf $NOVA_DIR/nova.sqlite

echo "--dhcpbridge_flagfile=/etc/nova/nova.conf" >> $NOVA_CONF_DIR/$NOVA_CONF
echo "--dhcpbridge=/usr/bin/nova-dhcpbridge" >> $NOVA_CONF_DIR/$NOVA_CONF
echo "--logdir=/var/log/nova" >> $NOVA_CONF_DIR/$NOVA_CONF
echo "--state_path=/var/lib/nova" >> $NOVA_CONF_DIR/$NOVA_CONF
echo "--lock_path=/var/lock/nova" >> $NOVA_CONF_DIR/$NOVA_CONF
echo "--flagfile=/etc/nova/nova-compute.conf" >> $NOVA_CONF_DIR/$NOVA_CONF
echo "--use_deprecated_auth" >> $NOVA_CONF_DIR/$NOVA_CONF
echo "--verbose" >> $NOVA_CONF_DIR/$NOVA_CONF
echo "--sql_connection=mysql://$NOVA_DB_USERNAME:$NOVA_DB_PASSWD@$PUBLIC_IP/nova" >> $NOVA_CONF_DIR/$NOVA_CONF
echo "--rabbit_host=$PUBLIC_IP" >> $NOVA_CONF_DIR/$NOVA_CONF
echo "--ec2_api=$PUBLIC_IP" >> $NOVA_CONF_DIR/$NOVA_CONF
echo "--ec2_url=http://$PUBLIC_IP:8773/services/Cloud" >> $NOVA_CONF_DIR/$NOVA_CONF
echo "--network_manager=nova.network.manager.FlatDHCPManager" >> $NOVA_CONF_DIR/$NOVA_CONF
echo "--fixed_range=$FIXED_RANGE_PREFIX.0/24" >> $NOVA_CONF_DIR/$NOVA_CONF
echo "--flat_network_dhcp_start=$FIXED_RANGE_PREFIX.2" >> $NOVA_CONF_DIR/$NOVA_CONF
echo "--network_size=255" >> $NOVA_CONF_DIR/$NOVA_CONF
echo "--glance_api_servers=$PRIVATE_IP:9292" >> $NOVA_CONF_DIR/$NOVA_CONF
echo "--network_host=$PUBLIC_IP" >> $NOVA_CONF_DIR/$NOVA_CONF
echo "--flat_network_bridge=br100" >> $NOVA_CONF_DIR/$NOVA_CONF
echo "--routing_source_ip=$PUBLIC_IP" >> $NOVA_CONF_DIR/$NOVA_CONF
echo "--s3_host=$PUBLIC_IP" >> $NOVA_CONF_DIR/$NOVA_CONF

#do we support KVM?
if ! sudo kvm-ok 1>/dev/null 2>&1; then
sudo sed -i -e "s/kvm/qemu/" /etc/nova/nova-compute.conf
fi

sudo chown -R root:nova $NOVA_CONF_DIR
sudo chmod 644 $NOVA_CONF_DIR/$NOVA_CONF

# restart all service
#sudo stop libvirt-bin
#sudo start libvirt-bin
#sudo stop nova-network
#sudo start nova-network
#sudo stop nova-compute
#sudo start nova-compute
#sudo stop nova-api
#sudo start nova-api
#sudo stop nova-objectstore
#sudo start nova-objectstore
#sudo stop nova-scheduler
#sudo start nova-scheduler
#sudo stop nova-volume
#sudo start nova-volume
#sudo stop glance-api
#sudo start glance-api
#sudo stop glance-registry
#sudo start glance-registry
#sudo restart libvirt-bin
if ! ps aux | grep libvirt-bin | grep -q -v grep; then sudo start libvirt-bin; fi
sudo restart nova-network
if ! ps aux | grep nova-network | grep -q -v grep; then sudo start nova-network; fi
sudo restart nova-compute
if ! ps aux | grep nova-compute | grep -q -v grep; then sudo start nova-compute; fi
sudo restart nova-api
if ! ps aux | grep nova-api | grep -q -v grep; then sudo start nova-api; fi
sudo restart nova-objectstore
if ! ps aux | grep nova-objectstore | grep -q -v grep; then sudo start nova-objectstore; fi
sudo restart nova-scheduler
if ! ps aux | grep nova-scheduler | grep -q -v grep; then sudo start nova-scheduler; fi
sudo restart nova-volume
if ! ps aux | grep nova-volume | grep -q -v grep; then sudo start nova-volume; fi
sudo restart glance-api
if ! ps aux | grep glance-api | grep -q -v grep; then sudo start glance-api; fi
sudo restart glance-registry
if ! ps aux | grep glance-registry | grep -q -v grep; then sudo start glance-registry; fi

#-- nova db setup
NOVA_USER=${NOVA_USER:-"user1"}
NOVA_PROJECT=${NOVA_PROJECT:-"project1"}
sudo nova-manage db sync
sudo nova-manage user admin $NOVA_USER
sudo nova-manage project create $NOVA_PROJECT $NOVA_USER
sudo nova-manage network create public $FIXED_RANGE_PREFIX.0/24 1 128 --bridge_interface eth0
if ! ps aux | grep libvirt-bin | grep -q -v grep; then sudo start libvirt-bin; fi
sudo restart nova-network
if ! ps aux | grep nova-network | grep -q -v grep; then sudo start nova-network; fi
sudo restart nova-compute
if ! ps aux | grep nova-compute | grep -q -v grep; then sudo start nova-compute; fi
sudo restart nova-api
if ! ps aux | grep nova-api | grep -q -v grep; then sudo start nova-api; fi
sudo restart nova-objectstore
if ! ps aux | grep nova-objectstore | grep -q -v grep; then sudo start nova-objectstore; fi
sudo restart nova-scheduler
if ! ps aux | grep nova-scheduler | grep -q -v grep; then sudo start nova-scheduler; fi
sudo restart nova-volume
if ! ps aux | grep nova-volume | grep -q -v grep; then sudo start nova-volume; fi
sudo restart glance-api
if ! ps aux | grep glance-api | grep -q -v grep; then sudo start glance-api; fi
sudo restart glance-registry
if ! ps aux | grep glance-registry | grep -q -v grep; then sudo start glance-registry; fi

sudo nova-manage project zipfile $NOVA_PROJECT $NOVA_USER
unzip nova.zip
EC2_ACCESS_KEY_LINE=`sudo nova-manage user exports $NOVA_USER | grep 'export EC2_ACCESS_KEY'`":$NOVA_PROJECT"
sed -i 's/^export EC2_ACCESS_KEY.*/'"$EC2_ACCESS_KEY_LINE"'/g' novarc
. $TOP_DIR/novarc
KEYPAIR_NAME=${KEYPAIR_NAME:-"mykey"}
euca-add-keypair $KEYPAIR_NAME > $KEYPAIR_NAME.pem
chmod 600 $KEYPAIR_NAME.pem
if ! grep -q "$TOP_DIR/novarc" /root/.bashrc; then
	echo "source $TOP_DIR/novarc" >> /root/.bashrc
fi
	
# Verifying the Image Service Installation
IMAGES_DIR=${IMAGES_DIR:-"/images"}
if [ ! -d $IMAGES_DIR ]; then
	mkdir $IMAGES_DIR
fi
cd $IMAGES
if [ ! -f $IMAGES_DIR/ttylinux-uec-amd64-12.1_2.6.35-22_1.tar.gz ]; then
	wget http://smoser.brickies.net/ubuntu/ttylinux-uec/ttylinux-uec-amd64-12.1_2.6.35-22_1.tar.gz -P $IMAGES_DIR
fi
AMI_DIR=${AMI_DIR:-"/var/lib/glance/images"}
rm -rf $AMI_DIR/*
rm -rf /tmp/*
IMAGE=`euca-describe-images | grep machine | cut -f2 | head -n1`
if [ -n $IMAGE ]; then
	cloud-publish-tarball $IMAGES_DIR/ttylinux-uec-amd64-12.1_2.6.35-22_1.tar.gz bucket1 amd64
fi
cd $TOP_DIR
IMAGE=`euca-describe-images | grep machine | cut -f2 | head -n1`
AVAILABLE_TIMEOUT=${AVAILABLE_TIMEOUT:-30}
if ! timeout $AVAILABLE_TIMEOUT sh -c "while ! euca-describe-images $IMAGE | grep -q available; do sleep 1; done"; then
	echo "Image $IMAGES didn't become available in $AVAILABLE_TIMEOUT"
	exit 1
fi

# floating ips
# Default floating IP pool name
INSTANCE_TYPE=${INSTANCE_TYPE:-"m1.tiny"}
INSTANCE_ID=`euca-run-instances $IMAGE -k $KEYPAIR_NAME -t $INSTANCE_TYPE | grep INSTANCE | cut -f2`
ACTIVE_TIMEOUT=${ACTIVE_TIMEOUT:-45}
if ! timeout $ACTIVE_TIMEOUT sh -c "while ! euca-describe-instances $INSTANCE_ID | grep -q running; do sleep 1; done"; then
	echo "Instance $INSTANCE_ID didn't become active in $ACTIVE_TIMEOUT"
	exit 1
fi
DEFAULT_FLOATING_POOL=${DEFAULT_FLOATING_POOL:-"nova"}
FLOATING_RANGE=${FLOATING_RANGE:-"192.168.168.224/28"}
INSTANCE_IP=`euca-describe-instances $INSTANCE_ID | grep INSTANCE | cut -f4`
sudo nova-manage floating create $FLOATING_RANGE
FLOATING_IP=`euca-allocate-address | cut -f2`
euca-associate-address -i $INSTANCE_ID $FLOATING_IP
euca-authorize -P icmp -t -1:-1 default
euca-authorize -P tcp -p 22 default

exit 0
